package com.xmler.plugin.adbrocket.utils

import com.android.ddmlib.IDevice
import com.android.tools.idea.gradle.project.sync.GradleSyncState
import com.intellij.openapi.project.Project
import com.xmler.plugin.adbrocket.adb.command.receiver.GenerateReceiver
import com.xmler.plugin.adbrocket.adb.command.receiver.TextLineLastReceiver
import java.util.concurrent.TimeUnit
import kotlin.math.pow
import kotlin.math.sqrt

object AdbUtil {
    /**
     * 判断当前Gradle是否正在执行sync操作
     */
    fun isGradleSyncInProgress(project: Project): Boolean {
        return try {
            GradleSyncState.getInstance(project).isSyncInProgress
        } catch (e: Throwable) {

            false
        }
    }

    fun isAppInstalld(device: IDevice, packageName: String): Boolean {
        val receiver = GenerateReceiver()
        device.executeShellCommand("pm list packages $packageName", receiver, 10L, TimeUnit.SECONDS)

        return receiver.outputLines.isNotEmpty()
    }

    fun getScreenSize(line: String?): Array<String> {
        var ret = line?.let {
            val regex = Regex("(?<=init\\=)[0-9]{1,}x[0-9]{1,}")
            regex.find(it)?.value?.split("x")?.toTypedArray()
        } ?: Array<String>(2)  {
            "0"
        }
        return ret
    }

    fun getScreenInch(screenSize: Array<String>, densityDpi: Double): Double {
        val size = screenSize.map {
            it.toInt()
        }
        val x = (size[0] / densityDpi).pow(2.0)
        val y = (size[1] / densityDpi).pow(2.0)
        return sqrt(x + y)
    }

    fun getHdpiString(densityDpi: Double): String {
        val dpi = densityDpi / 160
        return "x".repeat(dpi.toInt()) + "hdpi"
    }
}